<script setup lang="ts">
import AppTable from "@/components/app/AppTable.vue";
import {saveUser, updateUser, deleteUser, queryRoleList, deptList} from "@/api/system"
import {ElMessage, ElMessageBox} from "element-plus";
import {ref, reactive, onMounted} from "vue";
import type {ISysUserDTO} from "@/types";
import {getToken} from "@/utils/auth.ts";
import {apiPath} from "@/utils/request.ts";

defineOptions({
  // eslint-disable-next-line vue/multi-word-component-names
  name: "User"
})

const appTableRef = ref<InstanceType<typeof AppTable> | null>(null);
const formRef = ref();

// 表单数据
const formData = reactive<ISysUserDTO>({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  sex: '',
  status: '0',
  deptId: '',
  roles: [] as string[],
  avatar: ''
});
//当前操作用户id
const cuid = ref('');

// 表单验证规则
const formRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  nickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ],
  deptId: [
    {required: true, message: '请选择部门', trigger: 'change'}
  ],
  roleIds: [
    {required: true, message: '请选择角色', trigger: 'change', type: 'array'}
  ]
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);

// 部门和角色数据
const deptOptions = ref<any[]>([]);
const roleOptions = ref<any[]>([]);

// 获取部门和角色数据
const fetchDeptAndRoleData = async () => {
  try {
    // 获取部门数据
    const deptRes = await deptList();
    deptOptions.value = processDeptTree(deptRes.data || []);

    // 获取角色数据
    const roleRes = await queryRoleList();
    roleOptions.value = roleRes.data || [];
  } catch (error) {
    console.error(error);
  }
};

// 处理部门树形结构，添加缩进
const processDeptTree = (depts: any[], level = 0) => {
  const result: any[] = [];
  depts.forEach(dept => {
    // 添加当前部门
    result.push({
      ...dept,
      title: '　'.repeat(level) + dept.title // 添加缩进
    });

    // 递归处理子部门
    if (dept.children && dept.children.length > 0) {
      result.push(...processDeptTree(dept.children, level + 1));
    }
  });
  return result;
};

onMounted(() => {
  // 页面加载时获取部门和角色数据
  fetchDeptAndRoleData();
});

function handleBtnClick(key: string, data: any[] | null) {
  console.log(key, data)
  if (key === 'add') {
    handleAdd();
  }
  if (key === 'edit' && data) {
    handleEdit(data[0]);
  }
  if (key === 'delete' && data) {
    handleDelete(data[0].id);
  }
}

// 新增用户
const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增用户';
  isEdit.value = false;
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row: any) => {
  resetForm();
  dialogTitle.value = '编辑用户';
  isEdit.value = true;

  // 填充表单数据
  formData.username = row.username;
  formData.nickname = row.nickname;
  formData.phone = row.phone;
  formData.email = row.email;
  formData.sex = row.sex?.toString() || '';
  formData.status = row.status?.toString() || '0';
  formData.deptId = row.deptId !== null ? row.deptId : undefined;
  formData.avatar = row.avatar || '';
  formData.roles = row.roles.map(item => item.roleCode) || [];
  cuid.value = row.id;
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(id);
      ElMessage.success('删除成功');
      // 刷新表格
      if (appTableRef.value) {
        appTableRef.value.queryData();
      }
    } catch (error) {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    username: '',
    nickname: '',
    phone: '',
    email: '',
    sex: '',
    status: '0',
    deptId: '',
    roles: [] as string[],
    avatar: ''
  });
};

// 保存用户
const saveUserHandler = async () => {
  // 表单验证
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确');
    return;
  }

  try {
    // 准备提交数据，确保类型正确
    const submitData: ISysUserDTO = {
      ...formData,
    };

    if (isEdit.value) {
      await updateUser(cuid.value, submitData);
      ElMessage.success('更新成功');
    } else {
      await saveUser(submitData);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    // 刷新表格
    if (appTableRef.value) {
      appTableRef.value.queryData();
    }
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    console.error(error);
  }
};

// 处理头像上传
const handleAvatarSuccess = (response: any) => {
  if (response && response.data) {
    formData.avatar = apiPath+"/" + response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error('头像上传失败');
  }
};

// 头像上传前的处理
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

</script>

<template>
  <div>
    <AppTable
      ref="appTableRef"
      title="用户管理"
      :search-info="[
        {
          label: '用户名',
          key: 'username',
          value: ''
        },
        {
          label: '昵称',
          key: 'nickname',
          value: ''
        },
        {
          label: '手机号',
          key: 'phone',
          value: ''
        },
        {
          label: '状态',
          key: 'status',
          value: '',
          type: 'select',
          options: [{
            value: '0',
            label: '启用'
          }, {
            value: '1',
            label: '停用'
          }]
        },
      ]"
      :btn-show="{
        add: true,
        edit: true,
        delete: false,
        export: false,
        import: false
      }"
      api-method="get"
      api-path="/api/sys/user/list"
      @handle-btn-click="handleBtnClick"
      @multiple-selection="data => {console.log(data)}">
      <template v-slot:actionBar>
      </template>
      <template v-slot:tableColumn>
        <el-table-column label="头像" align="left" width="70">
          <template #default="scope">
            <el-avatar
              :src="scope.row.avatar"
            >
            {{ scope.row.nickname.substring(0,1) }}
          </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" align="left"/>
        <el-table-column prop="nickname" label="昵称" align="left"/>
        <el-table-column prop="sex" label="性别" width="60" align="left">
          <template #default="scope">
            <span>{{ scope.row.sex === '1' ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" align="left"/>
        <el-table-column prop="phone" label="手机号" align="left"/>
        <el-table-column prop="email" label="电子邮箱" align="left"/>
        <el-table-column prop="roles" label="角色" align="left">
          <template #default="scope">
              <el-tag v-for="role in scope.row.roles||[]" :key="role"
                      style="margin-right: 5px;" size="small">
                {{ role.roleName }}
              </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="70" align="left">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" table-fixed="table-fixed">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </AppTable>

    <!-- 用户编辑/新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="() => { dialogVisible = false }"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        label-width="80px"
        ref="formRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" :disabled="isEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="formData.nickname"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="1"/>
                <el-option label="女" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="0"/>
                <el-option label="停用" value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="formData.deptId" placeholder="请选择部门" style="width: 100%">
                <el-option
                  v-for="dept in deptOptions"
                  :key="dept.key"
                  :label="dept.title"
                  :value="dept.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roles">
              <el-select
                v-model="formData.roles"
                placeholder="请选择角色"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="role in roleOptions"
                  :key="role.value"
                  :label="role.label"
                  :value="role.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :action="apiPath+'/api/sys/file/upload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="{ Authorization: getToken() }"
              >
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUserHandler">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 为部门选项添加样式，使缩进更明显 */
:deep(.el-select-dropdown__item) {
  white-space: pre;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
